using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DIS_Client.MainManagers
{
	#region using
	using DevComponents.DotNetBar;
	using DIS_Client.Helpers;
	using System.Data;
	using System.Drawing;
	using System.IO;
	using DIS_Client.DIS_BUS_WS;
	#endregion
	public partial class FrmDetailOfOrder : Office2007Form
	{
		private DataTable DataSource;
		private int ID;

        public FrmDetailOfOrder(int id = -1)
		{
			InitializeComponent();
			ID = id;
		}

		private void FrmCreateOrders_Load(object sender, EventArgs e)
		{
			InitGridView();
			InitDataSource();
			if (ID != -1)
			{
				LoadOrders();
			}
		}

		private void InitGridView()
		{
            DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "IDOrderDetail",
                DataPropertyName = "IDOrderDetail",
                Name = "IDOrderDetail",
                Visible = false
			};
			dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "IDItem",
                DataPropertyName = "IDItem",
                Name = "IDItem",
                Visible = false
            };
            dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Item",
                DataPropertyName = "Item",
                Name = "Item",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 4))
            };
            dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Quantity",
				DataPropertyName = "Quantity",
				Name = "Quantity",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/4))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Price",
				DataPropertyName = "Price",
				Name = "Price",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/4))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Discount",
				DataPropertyName = "Discount",
				Name = "Discount",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/4)) - 1
			};
			dtgvData.Columns.Add(objColumn);
		}

		public void InitDataSource()
		{
			DataSource = new DataTable();
            DataSource.Columns.Add("IDOrderDetail");
            DataSource.Columns.Add("IDItem");
            DataSource.Columns.Add("Item");
			DataSource.Columns.Add("Quantity");
			DataSource.Columns.Add("Price");
			DataSource.Columns.Add("Discount");
			DataView objTimeSheetDV = new System.Data.DataView(DataSource);
			objTimeSheetDV.AllowNew = false;
			dtgvData.AutoGenerateColumns = false;
			dtgvData.DataSource = objTimeSheetDV;
			dtgvData.ClearSelection();
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			FrmUpdateOrderDetail frm = new FrmUpdateOrderDetail();
			frm.Handler += GetOrderDetail;
			frm.ShowDialog();
		}

		public void GetOrderDetail(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
			var item = BusService.Instance.Item_SelectByID(int.Parse(comp[0]));
			if(item != null)
			{
				DataSource.Rows.Add(string.Empty, item.ID, item.Name, comp[1], comp[2], comp[3]);
			}
		}


		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (DataSource.Rows.Count > 0)
			{
				DataSource.Rows.RemoveAt(dtgvData.SelectedRows[0].Index);
			}
		}

		private bool ValidateInput(ref string errorText)
		{
			if (DataSource.Rows.Count == 0)
			{
				errorText = "List is empty!";
				return false;
			}
            if (dtOrderDate.Value == DateTime.MinValue)
            {
                errorText = "Please select order date!";
                return false;
            }
			return true;
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			var errorText = "";
			bool success = false;
			if (!ValidateInput(ref errorText))
			{
				MessageBoxEx.Show(errorText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (ActionUpdate())
			{
				success = true;
			}
			if (success)
			{
				MessageBoxEx.Show(CommonHelper.GetMessage("Update", "Successful"), "Information",  MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
			{
                MessageBoxEx.Show(CommonHelper.GetMessage("Update", "Fail"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnExit_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private bool ActionUpdate()
		{
            try
            {
                if (ID != -1)
                {
                    var orders = BusService.Instance.Orders_SelectByID(ID);
                    if (orders != null)
                    {
                        orders.IsVerified = ckbxIsVerified.Checked;
                        orders.IsShipped = ckbxIsShipped.Checked;
                        orders.IsPaid = ckbxIsPaid.Checked;
                        if (BusService.Instance.Orders_Update(orders))
                        {
                            // Remove all order details of this order
                            if (BusService.Instance.OrderDetail_DeleteByOrder(ID))
                            {
                                // Re-Insert order details from list
                                for (int i = 0; i <= DataSource.Rows.Count - 1; i++)
                                {
                                    var orderdetail = new OrderDetailDTO
                                    {
                                        IDOrder = ID,
                                        IDItem = int.Parse(DataSource.Rows[i]["IDItem"].ToString()),
                                        Quantity = int.Parse(DataSource.Rows[i]["Quantity"].ToString()),
                                        Price = long.Parse(DataSource.Rows[i]["Price"].ToString()),
                                        Discount = double.Parse(DataSource.Rows[i]["Discount"].ToString()),
                                    };
                                    if (!BusService.Instance.OrderDetail_Insert(orderdetail))
                                    {
                                        //return false;
                                    }
                                }
                                return true;
                            }
                        }
                    }
                }
                else
                {
                    var orders = new OrdersDTO
                    {
                        IDChemistWareHouse = GlobalVariables.g_CurrentUser.IDChemistWareHouse,
                        OrderDate = dtOrderDate.Value,
                        IsVerified = ckbxIsVerified.Checked,
                        IsShipped = ckbxIsShipped.Checked,
                        IsPaid = ckbxIsPaid.Checked
                    };
                    if (BusService.Instance.Orders_Insert(ref orders))
                    {
                        for (int i = 0; i <= DataSource.Rows.Count - 1; i++)
                        {
                            var orderdetail = new OrderDetailDTO
                            {
                                IDOrder = orders.ID,
                                IDItem = int.Parse(DataSource.Rows[i]["IDItem"].ToString()),
                                Quantity = int.Parse(DataSource.Rows[i]["Quantity"].ToString()),
                                Price = long.Parse(DataSource.Rows[i]["Price"].ToString()),
                                Discount = DataSource.Rows[i]["Discount"].ToString() != string.Empty ? double.Parse(DataSource.Rows[i]["Discount"].ToString()) : 0,
                            };
                            if (!BusService.Instance.OrderDetail_Insert(orderdetail))
                            {
                                //return false;
                            }
                        }
                        return true;
                    }
                }
                return false;
            }
            catch
            {
                return false;
            }
		}

		private void LoadOrders()
		{
            var orders = BusService.Instance.Orders_SelectByID(ID);
            if (orders != null)
            {
                txtID.Text = ID.ToString();
                dtOrderDate.Value = orders.OrderDate;
                ckbxIsVerified.Checked = orders.IsVerified;
                ckbxIsShipped.Checked = orders.IsShipped;
                ckbxIsPaid.Checked = orders.IsPaid;
                LoadOrderDetail(orders);
            }
		}

		private void LoadOrderDetail(OrdersDTO orders)
		{
            var lst = BusService.Instance.OrderDetail_SelectByIDOrder(orders.ID);
            if (lst.Length > 0)
            {
                foreach (var item in lst)
                {
                    DataSource.Rows.Add(item.IDOrder, item.IDItem, item.Item.Name, item.Quantity, item.Price, item.Discount);
                }
            }
		}

        private void FrmCreateOrders_FormClosed(object sender, FormClosedEventArgs e)
        {
        }
	}
}